package com.evl.task;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.evl.api.ticket.service.ITicketService;
import com.evl.api.ticket.vo.SearchTrainRS;
import com.evl.common.constant.Const;
import com.evl.common.persistence.dao.ScheduleStationMapper;
import com.evl.common.persistence.dao.StationSeatRMapper;
import com.evl.common.persistence.dao.TicketRemainderMapper;
import com.evl.common.persistence.dao.TrainSeatScheduleMapper;
import com.evl.common.persistence.dao.VehicleScheduleMapper;
import com.evl.common.persistence.model.ScheduleStation;
import com.evl.common.persistence.model.TicketRemainder;
import com.evl.common.persistence.model.VehicleSchedule;
import com.evl.constant.TrainSeatType;
import com.evl.core.cache.CacheKit;
import com.evl.ticketRemainder.service.ITicketRemainderService;
import com.evl.ticketRemainder.vo.TrainSeatScheduleVo;
import com.evl.trainSeat.service.ITrainSeatService;
import com.evl.utils.DateUtils;
import com.evl.utils.JsonUtils;

@Component
public class TicketRemainderTask {

	@Resource
	VehicleScheduleMapper vehicleScheduleMapper;
	
	@Resource
	ScheduleStationMapper scheduleStationMapper;
	
	@Resource
	TrainSeatScheduleMapper trainSeatScheduleMapper;
	
	@Resource
	StationSeatRMapper stationSeatRMapper;
	
	@Resource
	TicketRemainderMapper ticketRemainderMapper;
	
	@Resource
	ITrainSeatService trainSeatService;
	
	@Resource
	ITicketService ticketService;
	
	@Resource
    ITicketRemainderService ticketRemainderService;
	
	private Logger log = Logger.getLogger(this.getClass());
	
	/**
	 * 后台定时更新余票池信息
	 * 单线程 --(多线程需要要自行编写实现)
	 */
	@Scheduled(cron="0 0/2 * * * ?") //间隔2分钟执行
	public void updateTicketRemainder() {
		
		//查询发车时间大于当前时间的调度车次
		List<VehicleSchedule> vehicleSchedules = vehicleScheduleMapper.selectVehicleScheduleByNow(DateUtils.getCurrentDateTime());
			
		//查询余票信息列表
		List<TicketRemainder> ticketRemainders = ticketRemainderMapper.selectTicketRemaindersByStaIds(vehicleSchedules);
		for (TicketRemainder ticketRemainder : ticketRemainders){
			
			List<ScheduleStation> subStations = trainSeatService.getStationLine(String.valueOf(ticketRemainder.getStaId()), ticketRemainder.getDeparture(), ticketRemainder.getArrive());
			
			//获取对应站点的座位列表（可选）存入map集合
			Map<Integer,List<TrainSeatScheduleVo>> map = new HashMap<Integer, List<TrainSeatScheduleVo>>();
			for (ScheduleStation ss : subStations){
				map.put(ss.getId(), trainSeatScheduleMapper.selectTrainSeatSchedulesByStationId(ss.getId()));
			}
			
			//获取每个站点的座位列表（可选）的交集
			List<TrainSeatScheduleVo> intersectionList = new ArrayList<TrainSeatScheduleVo>();
			for(Map.Entry<Integer, List<TrainSeatScheduleVo>> entry : map.entrySet()){
				if(intersectionList.size() == 0){//如何集合为空，赋值
					intersectionList = entry.getValue();
				} else{//取各个站点的集合交集
					intersectionList.retainAll(entry.getValue());
				}
			}
			
			//计算每种席别的座位
			Map<String,Integer> seatDetailMap = new HashMap<String, Integer>();
			
			//遍历席别枚举类，初始化数据
			for (TrainSeatType e : TrainSeatType.values()) {
				seatDetailMap.put(String.valueOf(e.code), 0);
			}
			
			for(int i=0; i<intersectionList.size(); i++){
				seatDetailMap.put(intersectionList.get(i).getSeatType(),(seatDetailMap.get(intersectionList.get(i).getSeatType())==null?0:seatDetailMap.get(intersectionList.get(i).getSeatType()))+1);
			}
			
			
			String seatDetail =JsonUtils.toJson(seatDetailMap);
			ticketRemainder.setTicketCount(intersectionList.size());
			ticketRemainder.setSeatDetail(seatDetail);
			
		}
		
		try {
			//批量更新余票信息
			ticketRemainderMapper.batchUpdateRemainders(ticketRemainders);
			
			/*
			 * 更新所有余票缓存
			 */
			Map<String,TicketRemainder> map = new HashMap<String, TicketRemainder>();
			for (TicketRemainder tr : ticketRemainders){
				String travelDate = DateUtils.getSpecifyDate(tr.getStartTime(), DateUtils.FORMAT_YYYY_MM_DD);
				map.put(tr.getDeparture()+"_"+tr.getArrive()+"_"+travelDate, tr);
			}

			for (Map.Entry<String,TicketRemainder> entry : map.entrySet()){
				
				List<SearchTrainRS> result = new ArrayList<SearchTrainRS>();
				
				TicketRemainder ticketRemainder = entry.getValue();
				String travelDate = DateUtils.getSpecifyDate(ticketRemainder.getStartTime(), DateUtils.FORMAT_YYYY_MM_DD);
				List<TicketRemainder> list =  ticketRemainderService.selectTicketRemainders(ticketRemainder.getDeparture(),ticketRemainder.getArrive(),travelDate);
	    		
	    		//封装数据给前端使用
	    		for (TicketRemainder tr :list){
	    			
	    			SearchTrainRS srs = ticketService.transformSearchTrainRS(tr, false);
	    			
	    			result.add(srs);
	    		}
				//将查询的列车余票信息存入缓存
				CacheKit.put(Const.TICKET_REMAINDER_LIST, entry.getKey(), result);
			}
			
			//更新查询的缓存
			List<?> cacheList = CacheKit.getKeys(Const.TICKET_REMAINDER_LIST);
			
			for(Object cacheKey :cacheList){
				if(map.get(String.valueOf(cacheKey)) ==null){
					
					String []keyArr = String.valueOf(cacheKey).split("_");
					List<TicketRemainder> list =  ticketRemainderService.selectTicketRemainders(keyArr[0],keyArr[1],keyArr[2]);
					
					List<SearchTrainRS> result = new ArrayList<SearchTrainRS>();
					//封装数据给前端使用
					for (TicketRemainder tr :list){
						
						SearchTrainRS srs = ticketService.transformSearchTrainRS(tr, false);
						
						result.add(srs);
					}
					
					//将查询的列车余票信息存入缓存
					CacheKit.put(Const.TICKET_REMAINDER_LIST, keyArr[0]+"_"+keyArr[1]+"_"+keyArr[2], result);
				}
	    		
			}
			
    		
    		/*
    		 * 更新所有单条余票详情存入缓存
    		 */
			for (TicketRemainder tr : ticketRemainders){
				
				SearchTrainRS ticketOne = ticketService.transformSearchTrainRS(tr,true);
				//将单条余票详情存入缓存
				CacheKit.put(Const.TICKET_REMAINDER_DETAIL,tr.getStaId()+"_"+tr.getDeparture()+"_"+tr.getArrive(),ticketOne);
			}
		
			log.info("定时刷新余票信息成功!");
		} catch (Exception e) {
			log.error("定时刷新余票操作数据库失败："+e.getMessage(), e);
		}
		
	}
		
}
